#!/bin/tcsh -fe
####
#
#############################################################################
#                                                                           #
# Title: Init Files and Parameters                                          #
#                                                                           #
# (C) 2dx.org, GNU Plublic License.                                         #
#                                                                           #
# Created..........: 03/21/2011                                             #
# Last Modification: 03/21/2011                                             #
# Author...........: 2dx.org                                                #
#                                                                           #
#############################################################################
#
# SORTORDER: 2
#
# MANUAL: <B>Welcome to 2dx_image</B>
#
# MANUAL: This program assists you in the processing of one 2D crystal image. Help is available <A HREF="http://2dx.org/documentation/2dx-software">here</A>. Try the right mouse click on the various fields or variable names, to get more information. See also the introductory <A HREF="http://2dx.org/documentation/2dx-software/tutorial"><B>Movie</B></A> tutorials.
#
# MANUAL: 2dx_image uses external programs to display certain files. These can be defined in the 2dx configuration file, which you can find (and edit) in your home directory under .2dx/2dx.cfg . Use this file to define your prefered editor, web browser, etc..
#
# MANUAL: Edit the parameters in this central <I>Processing Data</I> pane. By default, only the most important parameters are accessible here. If you want to change one of the <I>advanced</I> parameters too, you can switch the display mode of this <I>Processing Data</I> pane at the left end of the top bar from "Simplified" to "Full Parameter List".
#
# MANUAL: 2dx tries to calculate or predict values for all parameters, based on available information. In several cases, you need to manually verify these values. These are then unerlaid with a blue stripe-pattern, until you have edited or confirmed manually the values.   
#
# MANUAL: After having edited the parameters, choose a script from the <I>Standard Scripts</I> and execute it via the <I>Start</I> button above.
#
# MANUAL: Upon first launch of this program, a default database in form of the file 2dx_image.cfg is created in the chosen  directory. The default entries for this database file are taken from the ${appDir_2dx}2dx/config/2dx_image.cfg file. These default values are then updated with values from the file ../2dx_image.cfg (the database file one level up from the current directory). Finally, this script 2dx_initialize.script is executed, and the resulting databse saved into the local directory's 2dx_image.cfg file.
#
# MANUAL: <HR>
#
# MANUAL: <IMG SRC="${appDir_2dx}/../config/2dx_image-algo-1.jpg">
#
# MANUAL: <HR>
#
# MANUAL: <IMG SRC="${appDir_2dx}/../config/2dx_image-algo-2.jpg">
#
# DISPLAY: imagename_original
# DISPLAY: imagename
# DISPLAY: nonmaskimagename
# DISPLAY: imagenumber
# DISPLAY: magnification
# DISPLAY: stepdigitizer
# DISPLAY: Calc_from_sample_pixel
# DISPLAY: sample_pixel
# DISPLAY: realcell
# DISPLAY: realang
# DISPLAY: df_min
# DISPLAY: df_searchrange1
# DISPLAY: RESMAX
# DISPLAY: CS
# DISPLAY: KV
# DISPLAY: tempkeep
# DISPLAY: initialization_executable
# DISPLAY: initialization_corr_endian
# DISPLAY: det_defocus
# DISPLAY: det_tilt
# DISPLAY: crop
# DISPLAY: comment
# DISPLAY: imagesidelength
# DISPLAY: crop_histogram
# DISPLAY: crop_histogram_percent
# DISPLAY: crop_histogram_stdev
# DISPLAY: movie_stackname
# DISPLAY: movie_enable
# DISPLAY: movie_imagenumber_total
# DISPLAY: movie_imagenumber_touse
# DISPLAY: movie_imagenumber_toave
# DISPLAY: use_masked_image
#
#$end_local_vars
#
# Static directory variables at disposition are:
# appDir_2dx
# scripts-standard_2dx
# scripts-custom_2dx
#
set bin_2dx = ""
set proc_2dx = ""
set app_2dx_mrc_converter = ""
#
# Variables to be available from the config file are:
set tempkeep = ""
set imagename = ""
set nonmaskimagename = ""
set imagenumber = ""
set imagesidelength = ""
set realcell = ""
set magnification = ""
set stepdigitizer = ""
set Calc_from_sample_pixel = ""
set sample_pixel = ""
set realang = ""
set phacon = ""
set RESMIN = ""
set RESMAX = ""
set RADLIM = ""
set det_tilt = ""
set maska = ""
set maskb01 = ""
set maskb02 = ""
set maskb03 = ""
set maskb04 = ""
set maskb05 = ""
set boxa1 = ""
set boxa2 = ""
set boxb1 = ""
set boxb2 = ""
set quadrada = ""
set quadradb = ""
set initialization_executable = ""
set initialization_corr_endian = ""
set crop = ""
set MergeIWF = ""
set MergeIWP = ""
set crop_histogram = ""
set crop_histogram_percent = ""
set crop_histogram_stdev = ""
set movie_inmovie = ""
set movie_enable = ""
set movie_stackname = ""
set movie_imagenumber_total = ""
set movie_imagenumber_touse = ""
set movie_imagenumber_toave = ""
set use_masked_image = ""
set backup_large_images = ""
set CS = ""
set KV = ""
#
#$end_vars
#
set scriptname = 2dx_initialize_files
\rm -f LOGS/${scriptname}.results
#
set ccp4_setup = 'y'
set IS_2DX = yes
source ${proc_2dx}/initialize
#
#
# echo "set imagename = image_2dx"  >> LOGS/${scriptname}.results
# echo "set nonmaskimagename = image_2dx"  >> LOGS/${scriptname}.results
#
if ( ${movie_inmovie}x != "yx" ) then
  echo "<<@progress: 1>>"
  echo "<<@evaluate>>"
endif
#
if ( ${backup_large_images} == "yes" ) then
  set backup_large_images = 0
  echo "set backup_large_images = ${backup_large_images}" >> LOGS/${scriptname}.results
endif
#
if ( ! -e ${imagename}.mrc && ! -e ${imagename}_raw.mrc ) then
  set initialization_executable = 'y'
endif
#
if ( x${MergeIWF}x == "x-1x" ) then
  echo "set MergeIWF = 0" >> LOGS/${scriptname}.results
endif
#
if ( x${MergeIWP}x == "x-1x" ) then
  echo "set MergeIWP = 1" >> LOGS/${scriptname}.results
endif
#
set new_mrc_created = 'n'
set correct = 0
if ( ${backup_large_images}x == "yesx" ) then
  set backup_large_images = "0"
  echo "set backup_large_images = ${backup_large_images}" >> LOGS/${scriptname}.results
endif
#
set testname = `echo ${imagename} | cut -c2-`
if (( ${nonmaskimagename} != ${imagename} ) && ( ${nonmaskimagename} != ${testname} )) then
  set correct = 1
endif
if ( ${nonmaskimagename} == "ScriptWillPutNameHere" ) then
  set correct = 1
endif
if ( ${imagesidelength} == "ScriptWillPutLengthHere" ) then
  set correct = 1
  set new_mrc_created = 'y'
endif
#
if ( ${movie_inmovie}x == "yx" ) then
  set correct = 1
  set new_mrc_created = 'y'
endif
#
if ( ${movie_inmovie}x != "yx" ) then
  echo "<<@progress: 10>>"
endif
#
if ( ${CS} == "ScriptWillPutNumberHere" ) then
  set CS = ${Default_CS}
  echo "set CS = ${CS}" >> LOGS/${scriptname}.results
endif
#
if ( ${KV} == "ScriptWillPutNumberHere" ) then
  set KV = ${Default_KV}
  echo "set KV = ${KV}" >> LOGS/${scriptname}.results
endif
#
#################################################################################
${proc_2dx}/linblock "Sourcing 2dx_init_files_sub.com"
#################################################################################
#
${proc_2dx}/linblock "Pixel Size is ${sample_pixel}."
#
if ( ${sample_pixel}x == "x"  || ${sample_pixel} == "0" ) then
  ${proc_2dx}/linblock "WARNING: No valid Pixel Size found. Recalculating Pixel Size."
  set sample_pixel = `echo ${stepdigitizer} ${magnification} | awk '{ s = $1 * 10000.0 / $2 } END { print s }'`
  echo "set sample_pixel = ${sample_pixel}" >> LOGS/${scriptname}.results
  ${proc_2dx}/linblock "Calculating pixel size on sample level as ${sample_pixel} Angstroems."
endif
#
#
source ${proc_2dx}/2dx_init_files_sub.com
#
#
if ( ${movie_inmovie}x != "yx" ) then
  echo "<<@progress: 60>>"
endif
${proc_2dx}/linblock "Pixel Size is ${sample_pixel}."
#
if ( ${sample_pixel}x == "x"  || ${sample_pixel} == "0" ) then
  set Calc_from_sample_pixel = "n"  
  ${proc_2dx}/linblock "WARNING: No valid Pixel Size found. Recalculating Pixel Size."
endif
#
if ( ${Calc_from_sample_pixel} == "y" ) then
  set magnification = `echo ${stepdigitizer} ${sample_pixel} | awk '{ s = $1 * 10000.0 / $2 } END { print s }'`
  echo "set magnification = ${magnification}" >> LOGS/${scriptname}.results
  ${proc_2dx}/linblock "Calculating magnification as ${magnification}."
else
  set sample_pixel = `echo ${stepdigitizer} ${magnification} | awk '{ s = $1 * 10000.0 / $2 } END { print s }'`
  echo "set sample_pixel = ${sample_pixel}" >> LOGS/${scriptname}.results
  ${proc_2dx}/linblock "Calculating pixel size on sample level as ${sample_pixel} Angstroems."
endif
#
if ( ${initialization_executable} == "n" ) then
  #
  echo "Parameter initialization not done. Date: ${date}" >> History.dat
  #
  #################################################################################
  echo ":: "
  ${proc_2dx}/linblock "Parameter initialization ran already."
  echo "::If this is wrong, set 'Initialization can be executed (again)' to 'Yes'."
  echo ":: "
  #################################################################################
  #
else
  #
  echo "Parameter initialization starting. Date: ${date}" >> History.dat
  #
  #################################################################################
  #################################################################################
  echo ":: "
  ${proc_2dx}/linblock "Initializing parameters..."
  echo ":: "
  #################################################################################
  #################################################################################
  #
  #
  if ( `echo ${phacon} | awk '{ if (( $1 < 0 ) || ( $1 > 1 )) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
    set oldval = ${phacon}
    set phacon = 0.9975
    ${proc_2dx}/linblock "WARNING: correcting phacon from ${oldval} to ${phacon}"
    echo "set phacon = ${phacon}"  >> LOGS/${scriptname}.results
  endif
  #
  if ( `echo ${RESMIN} ${RESMAX} | awk '{ if ( $1 < $2 ) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
    set oldval = ${RESMIN}
    set RESMIN = ${RESMAX}
    set RESMAX = ${oldval}
    ${proc_2dx}/linblock "WARNING: exchanging RESMIN and RESMAX, to RESMIN=${RESMIN}, and RESMAX=${RESMAX}"
    echo "set RESMIN = ${RESMIN}"  >> LOGS/${scriptname}.results
    echo "set RESMAX = ${RESMAX}"  >> LOGS/${scriptname}.results
  endif
  #
  set testval1 = `echo ${RADLIM} | cut -d\, -f1`
  set testval2 = `echo ${RADLIM} | cut -d\, -f2`
  set testval3 = `echo ${RADLIM} | cut -d\, -f3`
  set correctit = 0
  #
  if ( `echo ${testval1} | awk '{ if (( $1 < 0 ) || ( $1 > 50 )) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
    set oldval = ${testval1}
    set testval1 = 35
    set correctit = 1 
    ${proc_2dx}/linblock "WARNING: correcting RADLIM first value from ${oldval} to ${testval1}"
  endif
  #
  if ( `echo ${testval2} | awk '{ if (( $1 < 0 ) || ( $1 > 50 )) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
    set oldval = ${testval2}
    set testval2 = 35
    set correctit = 1 
    ${proc_2dx}/linblock "WARNING: correcting RADLIM second value from ${oldval} to ${testval2}"
  endif
  #
  if ( ${correctit} == 1 ) then
    set RADLIM = `echo ${testval1},${testval2},${testval3}`
    echo "set RADLIM = ${RADLIM}"  >> LOGS/${scriptname}.results
  endif
  #
  set newimagenumber = `echo ${imagenumber} | ${bin_2dx}/2dx_getnumber.exe`
  if ( ${newimagenumber} != ${imagenumber} ) then
    ${proc_2dx}/linblock "WARNING: correcting imagenumber from ${imagenumber} to ${newimagenumber}"
    set imagenumber = ${newimagenumber}
    echo "set imagenumber = ${imagenumber}"  >> LOGS/${scriptname}.results
  endif
  #
  set testval = `echo ${imagenumber} | wc -c`
  if ( `echo ${testval} | awk '{ if ( $1 < 11 ) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
    set oldval = ${imagenumber}
    set imagenumber = `echo 0000000000 | cut -c${testval}-`${imagenumber}
    ${proc_2dx}/linblock "WARNING: correcting imagenumber from ${oldval} to ${imagenumber}"
    echo "set imagenumber = ${imagenumber}"  >> LOGS/${scriptname}.results
  endif  
  #
  if ( `echo ${testval} | awk '{ if ( $1 > 11 ) { s = 1 } else { s = 0 }} END { print s }'` == 1 ) then
    set oldval = ${imagenumber}
    set startnum = `echo ${testval} | awk '{ s = $1 - 10 } END { print s }'`
    set endnum   = `echo ${testval} | awk '{ s = $1 - 1 } END { print s }'`
    set imagenumber = `echo ${imagenumber} | cut -c${startnum}-${endnum}`
    ${proc_2dx}/linblock "WARNING: correcting imagenumber from ${oldval} to ${imagenumber}"
    echo "set imagenumber = ${imagenumber}"  >> LOGS/${scriptname}.results
  endif  
  #
  # maska and maskb01 to maskb05 are UnbendI and UnbendII Fourier masking diameters.
  #
  if ( ${maska} == "PutNumberHere" ) then
    set maska = `echo ${imagesidelength} ${realcell} | sed 's/,/ /g' | awk '{ s = int( $1 / ( 3.4 * $2 + 1) ) } END { print s }'`
    echo "set maska = ${maska}"  >> LOGS/${scriptname}.results
    echo ":Initializing maska as ${maska}"
  endif
  #
  if ( ${maskb01} == "PutNumberHere" ) then
    set maskb01 = `echo ${imagesidelength} ${realcell} | sed 's/,/ /g' | awk '{ s = int( $1 / ( 3.0 * $2 + 1) ) } END { print s }'`
    echo "set maskb01 = ${maskb01}"  >> LOGS/${scriptname}.results
    echo ":Initializing maskb01 as ${maskb01}"
  endif
  #
  if ( ${maskb02} == "PutNumberHere" ) then
    set maskb02 = `echo ${imagesidelength} ${realcell} | sed 's/,/ /g' | awk '{ s = int( $1 / ( 2.6 * $2 + 1) ) } END { print s }'`
    echo "set maskb02 = ${maskb02}"  >> LOGS/${scriptname}.results
    echo ":Initializing maskb02 as ${maskb02}"
  endif
  #
  # boxa1 and boxb1 are for the first UnbendI and following UnbendII reference diameters.
  #
  # Since the reference size heavily depends on the size of the image, they should always be initialized when the imagesidelenght is detected.
  #
  set boxa1 = `echo ${imagesidelength} | awk '{ s = int( $1 / 10 ) } END { print s }'`
  echo "set boxa1 = ${boxa1}"  >> LOGS/${scriptname}.results
  echo ":Initializing boxa1 as ${boxa1}"
  #
  set boxb1 = `echo ${imagesidelength} | awk '{ s = int( $1 / 13 ) } END { print s }'`
  echo "set boxb1 = ${boxb1}"  >> LOGS/${scriptname}.results
  echo ":Initializing boxb1 as ${boxb1}"
  #
  set movie_refboxa = `echo ${imagesidelength} | awk '{ s = int( $1 / 13 )  } END { print s }'`
  echo "set movie_refboxa = ${movie_refboxa}"  >> LOGS/${scriptname}.results
  echo ":Initializing movie_refboxa as ${movie_refboxa}"
  #
  # set movie_refboxb = `echo ${imagesidelength} | awk '{ s = int( $1 / 13 )  } END { print s }'`
  set movie_refboxb = 0
  echo "set movie_refboxb = ${movie_refboxb}"  >> LOGS/${scriptname}.results
  echo ":Initializing movie_refboxb as ${movie_refboxb}"
  #
  # boxa2 and boxb2 are for shifting SpotScan spots into their correct location. 
  # These references need to be much larger, optimally the diameter of one of the SpotScan spots.
  # This is only used if you have SpotScan spots (and set the corresponding flag to "y").
  #
  if ( ${boxa2} == "0" ) then
    set boxa2 = `echo ${imagesidelength} | awk '{ s = int( $1 / 4 )  } END { print s }'`
    echo "set boxa2 = ${boxa2}"  >> LOGS/${scriptname}.results
    echo ":Initializing boxa2 as ${boxa2}"
  endif
  #
  if ( ${boxb2} == "0" ) then
    set boxb2 = `echo ${imagesidelength} | awk '{ s = int( $1 / 4 )  } END { print s }'`
    echo "set boxb2 = ${boxb2}"  >> LOGS/${scriptname}.results
    echo ":Initializing boxb2 as ${boxb2}"
  endif
  #
  set quadraday = `echo ${quadrada}noval | cut -d\, -f2`
  if ( ${quadraday} == "noval" ) then
    set tmp = `echo ${quadrada} | cut -d\, -f1` 
    set quadrada = ${tmp},${tmp}
    ${proc_2dx}/linblock "WARNING: correcting quadrada to ${quadrada}"
    echo "set quadrada = ${quadrada}"  >> LOGS/${scriptname}.results
  endif
  #
  set quadradby = `echo ${quadradb}noval | cut -d\, -f2`
  if ( ${quadradby} == "noval" ) then
    set tmp = `echo ${quadradb} | cut -d\, -f1` 
    set quadradb = ${tmp},${tmp}
    ${proc_2dx}/linblock "WARNING: correcting quadradb to ${quadradb}"
    echo "set quadradb = ${quadradb}"  >> LOGS/${scriptname}.results
  endif
  #
  if ( ${initialization_executable} == "y" ) then
    set initialization_executable = "n"
    echo "set initialization_executable = ${initialization_executable}"  >> LOGS/${scriptname}.results
  endif
  # 
endif
#
if ( ${movie_inmovie}x != "yx" ) then
  echo "<<@progress: 80>>"
endif
#
#
if ( ${movie_enable} == "y" ) then
  ${proc_2dx}/linblock "Movie Mode."
  if ( ${movie_stackname} == "ScriptWillPutNameHere") then
    if( -e ${nonmaskimagename}_stack.mrc ) then
      \mv -f ${nonmaskimagename}_stack.mrc movie_aligned.mrcs
      set movie_stackname = movie_aligned
      echo "set movie_stackname = ${movie_stackname}"  >> LOGS/${scriptname}.results
    endif
  else
    if ( ! -e ${movie_stackname}.mrcs ) then
      if ( -e ${movie_stackname} ) then
        set firstpart = `echo ${movie_stackname} | rev | cut -d\. -f2- | rev`
        \mv -f ${movie_stackname} ${firstpart}.mrcs
        if ( -e ${firstpart}.mrcs ) then
          set movie_stackname = ${firstpart}
          echo "set movie_stackname = ${movie_stackname}" >> LOGS/${scriptname}.results
          #################################################################################
          ${proc_2dx}/linblock "Setting movie_stackname to ${movie_stackname}"
          #################################################################################
        endif
      endif
    endif
  endif
  if ( ! -e ${movie_stackname}.mrcs ) then
    ${proc_2dx}/linblock "ERROR: ${movie_stackname}.mrcs missing. Not processing in movie mode."
    set movie_enable = "n"
    echo "set movie_enable = ${movie_enable}" >> LOGS/${scriptname}.results
  else
    # Get the number of frames
    \rm -f dummy.mrc
    \ln -s ${movie_stackname}.mrcs dummy.mrc
    e2iminfo.py -H dummy.mrc > tmp_stack_header.txt
    \rm -f dummy.mrc
    set movie_imagenumber_total = `\grep "MRC.nz:" tmp_stack_header.txt | cut -d' ' -f 2`
    ${proc_2dx}/linblock "Stack contains ${movie_imagenumber_total} frames"
    echo "set movie_imagenumber_total = ${movie_imagenumber_total}"  >> LOGS/${scriptname}.results 

    set test = `echo ${movie_imagenumber_total} ${movie_imagenumber_toave} | awk '{s = int($1/$2) } END { print s }'`
	
    echo "set movie_imagenumber_touse = ${test}"  >> LOGS/${scriptname}.results
    \rm tmp_stack_header.txt
  endif
endif
#
#################################################################################
${proc_2dx}/linblock "Calculating Histogram of ${movie_stackname}"
#################################################################################
#
echo "# IMAGE-IMPORTANT: Histogram.png <Histogram (PNG)>"  >> LOGS/${scriptname}.results
source ${proc_2dx}/histogram_sub.com ${nonmaskimagename}
#
#
#
#
#################################################################################
#
echo "# IMAGE-IMPORTANT: ${nonmaskimagename}_raw.mrc <RAW Non-Masked Image>" >> LOGS/${scriptname}.results
if ( ${nonmaskimagename} != ${imagename} ) then
  echo "# IMAGE-IMPORTANT: ${imagename}.mrc <Image>"  >> LOGS/${scriptname}.results
endif
echo "# IMAGE-IMPORTANT: ${nonmaskimagename}.mrc <Non-Masked Image>" >> LOGS/${scriptname}.results
#
if ( ${movie_enable} == "n" ) then
  #
  # This is to make sure that 2dx_maskCrystal displays the three file names even before it has been run
  if ( ! -e LOGS/2dx_maskCrystal.results ) then
    echo "# IMAGE-IMPORTANT: ${nonmaskimagename}.mrc <Non-Masked Image>" >> LOGS/2dx_maskCrystal.results
    echo "# IMAGE-IMPORTANT: ManualMasking-CCmap.mrc <XCF map for Manual Masking>" >> LOGS/2dx_maskCrystal.results
    echo "# IMAGE-IMPORTANT: ManualMasking-UnbendPlot.mrc <Unbending Plot for Manual Masking>" >> LOGS/2dx_maskCrystal.results
  endif
  #
endif
#
#
#############################################################################
echo ":: "
${proc_2dx}/linblock "Done."
echo ":: "
#############################################################################
#
if ( ${movie_inmovie}x != "yx" ) then
  echo "<<@progress: 100>>"
  echo "<<@evaluate>>"
endif
#
exit
#
# These are listed here to make sure they appear in the 2dx_image GUI:
source ${proc_2dx}/2dx_initialize_tiff_to_mrc_sub.com
source ${proc_2dx}/2dx_initialize_test_endianess_of_mrc_sub.com
source ${proc_2dx}/2dx_initialize_make_image_square_sub.com
source ${proc_2dx}/2dx_initialize_crop_histogram_sub.com
source ${proc_2dx}/2dx_correctHeaderCell_sub.com
python ${proc_2dx}/movie/mask.py
source ${proc_2dx}/2dx_makedirs
#
